/**
 *@description 菜单操作页面js
 *@author XieXing
 *@date 2020/8/23 15:33
 */
var table, form, layer, laydate, layedit, tree, renderTable;//当前页面全局定义 TODO 继续优化
var module = {
    /**
     *@description 菜单操作接口url集合 统一管理
     *@author XieXing
     *@date 2020/8/23 15:35
     */
    URL: {
        getDataListUrl: '/menu/getMenuList',//获取菜单信息
        getTreeMenus: '/menu/getTreeMenus',//获取菜单树
        saveUrl: "/menu/save",//保存菜单信息
        updateUrl: '/menu/update',//修改菜单信息
        updateStatusUrl: function (id, status) {//更新菜单状态
            return '/menu/' + id + '/' + status;
        },
        deleteUrl: function (id) {//删除菜单
            return '/menu/' + id;
        }
    },
    /**
     *@description 初始化
     *@author XieXing
     *@date 2020/8/23 15:36
     */
    init: function () {
        layui.config({base: '/static/assets/layui-extends/'}).extend(
            {
                treetable: 'treetable'
            }
        ).use(['table', 'treetable', 'tree', 'form', 'layer', 'laydate', 'layedit'], function () {
            var treetable = layui.treetable;
            tree = layui.tree;
            table = layui.table;
            form = layui.form;
            layer = layui.layer;
            laydate = layui.laydate;
            layedit = layui.layedit;
            var loading = layer.load(1);

            /**
             *@description 菜单加载
             *@author XieXing
             *@date 2020/12/8 16:30
             */
            renderTable = function () {
                var tableHeight = $(window).height() - 180 - $("#queryForm").height();
                treetable.render({
                    treeColIndex: 1,          // treetable新增参数
                    treeSpid: 0,             // 顶级父id
                    treeIdName: 'id',       // treetable新增参数
                    treePidName: 'menuPid',     // treetable新增参数
                    treeDefaultClose: false,   // treetable新增参数
                    treeLinkage: true,        // treetable新增参数
                    elem: '#datagrid',
                    url: module.URL.getDataListUrl,/*换成你的接口*/
                    cols: [[
                        {field: 'id', title: '', width: '5%'},
                        {field: 'menuName', title: '菜单名称', width: '15%'},
                        {
                            field: 'menuCode',
                            title: '菜单编码',
                            width: '15%'
                        },
                        {
                            field: 'menuUrl',
                            title: '菜单url',
                            width: '15%'
                        },

                        {
                            field: 'menuPermission',
                            title: '菜单权限',
                            width: '15%'
                        },
                        {
                            field: 'menuType',
                            title: '菜单类型',
                            width: '10%',
                            templet: function (d) {
                                var str = "未知";
                                if (d.menuType == 1) {
                                    str = "菜单";
                                } else if (d.menuType == 2) {
                                    str = "导航";
                                } else if (d.menuType == 3) {
                                    str = "按钮";
                                }
                                return str;
                            }
                        },
                        {
                            field: '', title: '操作', width: '330',
                            templet: function (d) {
                                var str = "<button class='layui-btn layui-btn-normal layui-icon layui-icon-add-1' type='button' lay-event='add'>新增子菜单</button>";
                                str += "<button class='layui-btn layui-icon layui-icon-edit' type='button' lay-event='edit'>编辑</button>";
                                str += "<button class='layui-btn layui-btn-danger layui-icon layui-icon-delete' type='button' lay-event='del'>删除</button>";
                                return str;
                            }
                        }
                    ]],
                    height: tableHeight,
                    done: function (res, curr, count) {
                        layer.close(loading);//关闭延迟加载
                    }
                });
            };
            renderTable();
            /**
             *@description 菜单全部展开
             *@author XieXing
             *@date 2020/12/4 16:41
             */
            $('#expandBtn').click(function () {
                treetable.expandAll('#datagrid');
            });

            /**
             *@description 菜单全部折叠
             *@author XieXing
             *@date 2020/12/4 16:42
             */
            $('#foldBtn').click(function () {
                treetable.foldAll('#datagrid');
            });


            //监听单元格事件
            table.on('tool(datagrid)', function (obj) {
                var rowData = obj.data;
                //新增
                if (obj.event === 'add') {
                    $("#menuPid").val(rowData.id);
                    module.edit_model("新增菜单", module.URL.saveUrl, rowData);
                }
                //编辑
                if (obj.event === 'edit') {
                    module.edit_model("修改菜单", module.URL.updateUrl, rowData);
                }
                //删除
                if (obj.event === 'del') {
                    delMenu(rowData);
                }
            });

            /**
             *@description 新增导航
             *@author XieXing
             *@date 2020/12/8 16:23
             */
            $("#addBtn").click(function () {
                module.edit_model("新增导航", module.URL.saveUrl);
            });

            /**
             *@description 点击查询
             *@author XieXing
             *@date 2020/7/30 11:34
             */
            $("#btnSearch").on("click", function () {
                var qm = {};
                $("#queryForm").serializeArray().forEach(function (each) {
                    qm[each.name] = each.value;
                });
                var cur = parseInt($(".layui-laypage-skip input").val()) || 1;//当前页
                var limit = parseInt($(".layui-laypage-limits select").val()) || 10;//当前每页条数
                treetable.reload('datagrid', {
                    where: qm,
                    page: {curr: cur, limit: limit}
                });
                return false;
            });


            /**
             *@description 删除菜单
             *@author XieXing
             *@date 2020/12/8 16:21
             */
            function delMenu(rowData) {
                layer.confirm("确认删除菜单" + rowData.menuName + "吗？", function () {
                    var loading = layer.load(1);
                    $.post(module.URL.deleteUrl(rowData.id), {}, function (result) {
                        if (result && result.code === 200) {
                            layer.closeAll();
                            renderTable();
                        } else {
                            layer.close(loading);
                            layer.msg(result.err, {icon: 2, time: 2000});
                            return false;
                        }
                    });
                });
            }

        });
    },
    /**
     *@description 编辑弹出层
     *@author XieXing
     *@date 2020/8/18 22:00
     */
    edit_model: function (modelName, url, rowData) {
        layer.open({
            type: 1,
            area: ['80%', '60%'],
            title: modelName,
            content: $("#dataModel"),
            offset: ['20px'],
            btn: ['提交', '取消'],
            btn1: function (index, layero) {
                $("#formSubmitBtn").trigger("click");
                return false;
            },
            btn2: function (index, layero) {
                $("#dataModel form")[0].reset();
                layer.closeAll();
                return false;
            },
            cancel: function (layero, index) {
                $("#dataModel form")[0].reset();
                layer.closeAll();
            },
            success: function (layero, index) {
                if (modelName === "修改菜单") {
                    module.getData(rowData);//非新增操作回填数据
                    $("#menuPid").val(rowData.parentName);
                    if (rowData.menuPid == 0) {
                        $("#menuPid").val("无");
                    }
                }
                if (modelName === "新增菜单") {
                    $("#menuPid").val(rowData.menuName);
                    $("select[name='menuType']").val(1);
                    form.render();
                }
                if (modelName === "新增导航") {
                    $("#menuPid").val("无");
                    $("select[name='menuType']").val(2);
                    form.render();
                }
                form.on('submit(form_submit_btn)', function (data) {
                    var data = data.field;
                    if (modelName === "修改菜单") {
                        data.id = rowData.id;
                        data.menuPid = rowData.menuPid;
                    }
                    if (modelName === "新增菜单") {
                        data.menuPid = rowData.id;
                    }
                    if (modelName === "新增导航") {
                        data.menuPid = 0;
                    }
                    var loading = layer.load(1);
                    $.post(url, data, function (result) {
                        if (result && result.code === 200) {
                            layer.closeAll();
                            $("#dataModel form")[0].reset();
                            renderTable();
                        } else {
                            layer.close(loading);
                            layer.msg(result.err, {icon: 2, time: 2000});
                            return false;
                        }
                    });
                    return false;
                });
            }
        });
    },
    /**
     *@description 对象回填数据
     *@author XieXing
     *@date 2020/8/17 15:02
     */
    getData: function (data) {
        for (var k in data) {
            $("input[name=" + k + "],select[name=" + k + "],textarea[name=" + k + "]").val(data[k]);
        }
        form.render();
    }

};
module.init();//运行初始化函数
